using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.IO;

using EntLibEC.Cmn;

using EntLibEC.Info.Basic;
using EntLibEC.Info.Purchase;

using EntLibEC.Biz;
using EntLibEC.Biz.Basic;
using EntLibEC.Biz.Purchase;

namespace EntLibEC.View.Purchase
{
	/// <summary>
	/// Summary description for POPrint.
	/// </summary>
	public partial class POPrint : PageBase
	{

		private int sysno;
		protected string bodyOnLoad;

		private int lineInPage = 10;
		private string pageBreaker = "<p class=\"pager\"></p>";
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			//1 get sysno
			//2 get templet
			//3 replace templet
			
			if ( Request.QueryString["sysno"] == null )
			{
				Assert(lblMessage, "Request string missing", -1);
				return;
			}
			try
			{
				sysno = Int32.Parse(Request.QueryString["sysno"].ToString());
			}
			catch
			{
				Assert(lblMessage, "Request string error", -1);
				return;
			}

			bodyOnLoad = "javascript:window.print();window.close();";
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected string GetPrintContent()
		{
			
			string path = Server.MapPath(".");
			string fileName = "POPrintTemplet.htm";
			string filePath = path + @"\" + fileName;

			//base.LineInPage = Int32.Parse(hidLineInPage.Value);

			FileStream aFile;
			try
			{
				aFile = new FileStream(@filePath, FileMode.Open, FileAccess.Read);
			}
			catch
			{
				Assert(lblMessage, "templet file open error", -1);
				return "";
			}
			StreamReader sr = new StreamReader(aFile,System.Text.Encoding.GetEncoding("gb2312"));

			string templet = sr.ReadToEnd();
			sr.Close();
			
			// ~ Get Company Info
			//1 prepare the information of head execept "pager"
			//2 get headTemplet
			//3 fill in head by replace the key string.
			

			//~
			EntLibInfo cInfo = new EntLibInfo();


			//1
			POInfo a = PurchaseManager.GetInstance().LoadPO(this.sysno);
			if ( a == null )
			{
				Assert(lblMessage, "Load po Info Error", -1);
				return "";
			}

			VendorInfo oVendor = VendorManager.GetInstance().Load(a.VendorSysNo);

			StockInfo stock = StockManager.GetInstance().Load(a.StockSysNo);

			CurrencyInfo oCurrency = CurrencyManager.GetInstance().GetCurrencyHash()[a.CurrencySysNo] as CurrencyInfo;
			PayTypeInfo oPayType = ASPManager.GetInstance().LoadPayType(a.PayTypeSysNo);
			ShipTypeInfo oShipType = ASPManager.GetInstance().LoadShipType(a.ShipTypeSysNo);

			UserInfo oCreatUser = SysManager.GetInstance().LoadUser(a.CreateUserSysNo);

			//2
			string headTemplet = GetString( templet, "_beginHead", "_endHead");

			headTemplet = Rep( headTemplet, "_companyName", cInfo.CompanyName);
			headTemplet = Rep( headTemplet, "_companyAddress", cInfo.CompanyAddress);
			headTemplet = Rep( headTemplet, "_companyPhone", cInfo.CompanyTel);
			headTemplet = Rep( headTemplet, "_companyWebAddress", cInfo.CompanyWebSite);
			headTemplet = Rep( headTemplet, "_printTime", DateTime.Now.ToString(AppConst.DateFormat));

			headTemplet = Rep( headTemplet, "_vendorName", oVendor.VendorName);
			headTemplet = Rep( headTemplet, "_vendorAddress", oVendor.Address);
			headTemplet = Rep( headTemplet, "_vendorContact", oVendor.Contact);
			headTemplet = Rep( headTemplet, "_vendorTel", oVendor.Phone + " FAX : " + oVendor.Fax);

			headTemplet = Rep( headTemplet, "_stockAddress", cInfo.StockAddress);
			headTemplet = Rep( headTemplet, "_stockContact", cInfo.StockContact);
			headTemplet = Rep( headTemplet, "_stockTel", cInfo.StockTel);

			string inTime = "";
			if ( a.InTime != AppConst.DateTimeNull)
				inTime = a.InTime.ToString(AppConst.DateFormat);

			headTemplet = Rep( headTemplet, "_inTime", inTime);
			headTemplet = Rep( headTemplet, "_payType", oPayType.PayTypeName);
			headTemplet = Rep( headTemplet, "_shipType", oShipType.ShipTypeName);
			headTemplet = Rep( headTemplet, "_purchaseUser", oCreatUser.UserName);
			headTemplet = Rep( headTemplet, "_currency", oCurrency.CurrencyName);



			headTemplet = Rep( headTemplet, "_sheetno", a.POID);
			headTemplet = Rep( headTemplet, "_memo", a.Memo);

			//1 get body, from body we get body templet
			//2 get rowTemplet
			string body = GetString(templet, "_beginBody", "_endBody");
			string bodyTemplet = RepField(body, "_beginRow", "_endRow", "_bodyRows");

			string rowTemplet = GetString( templet, "_beginRow", "_endRow");
			string rawRow;

			string footTemplet = GetString(templet, "_beginFoot", "_endFoot");
			
			string bodyRows = "";

			Hashtable itemHash = a.itemHash;
	

			// calc totalPage
			int totalPage= itemHash.Count / lineInPage;
			if ( itemHash.Count % lineInPage != 0 )
			{
				totalPage++;
			}

			int pageCounter = 0;
			int lineCounter = 0;

			string content = "";
			decimal totalInPage = 0;
			
			Hashtable sysnoHt = new Hashtable(5);
			foreach(POItemInfo itemInfo in itemHash.Values)
			{
				sysnoHt.Add(itemInfo.ProductSysNo, null);
			}
			Hashtable productHt = ProductManager.GetInstance().GetProductBoundle(sysnoHt);

			foreach(POItemInfo item in itemHash.Values)
			{
				lineCounter++;

				ProductBasicInfo oProduct = productHt[item.ProductSysNo] as ProductBasicInfo;

				rawRow = rowTemplet;
				rawRow = Rep( rawRow, "_productId", oProduct.ProductID);
				rawRow = Rep( rawRow, "_productName", oProduct.BriefName);
				rawRow = Rep( rawRow, "_productMode", oProduct.ProductMode);
				rawRow = Rep( rawRow, "_quantity", item.Quantity.ToString());
				rawRow = Rep( rawRow, "_orderPrice", oCurrency.CurrencySymbol + item.OrderPrice.ToString(AppConst.DecimalFormat));
				rawRow = Rep( rawRow, "_lineCost", (item.Quantity*item.OrderPrice).ToString(AppConst.DecimalFormat));

				totalInPage += item.Quantity*item.OrderPrice;

				bodyRows += rawRow;

				if (lineCounter % lineInPage == 0 )
				{//need page breaker
					pageCounter++;
					content += Rep( headTemplet, "_pager", pageCounter.ToString() + " of " + totalPage.ToString() );
					content += Rep( bodyTemplet, "_bodyRows", bodyRows);
					string foot = Rep( footTemplet, "_totalInPage", oCurrency.CurrencySymbol + totalInPage.ToString(AppConst.DecimalFormat));
					content += Rep( foot, "_totalAmt", oCurrency.CurrencySymbol + a.TotalAmt.ToString(AppConst.DecimalFormat));
					totalInPage = 0;
					if ( pageCounter != totalPage)
						content += pageBreaker;
					bodyRows = "";	
				}
			}

			if ( pageCounter != totalPage )
			{
				pageCounter++;
				content += Rep( headTemplet, "_pager", pageCounter.ToString() + " of " + totalPage.ToString() );
				content += Rep( bodyTemplet, "_bodyRows", bodyRows);
				string foot = Rep( footTemplet, "_totalInPage", oCurrency.CurrencySymbol + totalInPage.ToString(AppConst.DecimalFormat));
				content += Rep( foot, "_totalAmt", oCurrency.CurrencySymbol + a.TotalAmt.ToString(AppConst.DecimalFormat));
			}

			return content;

		}

		private string Rep(string org, string source, string target)
		{
			return Rep( org, source, target, 0);
		}
		private string Rep( string org, string source, string target, int len)
		{
			if ( len != 0 )
			{
				if ( target.Length>len )
				{
					target = target.Substring(0, len);
				}
			}
			return org.Replace(source, target);
		}
		private string RepField(string org, string beginTag, string endTag, string block)
		{
			int beginIndex, endIndex;
			string result;

			beginIndex = org.IndexOf( beginTag, 0 );
			endIndex	= org.IndexOf( endTag, 0 );
			if ( endIndex <= beginIndex )
			{
				return org;
			}
			else
			{
				result = org.Substring(0, beginIndex) + org.Substring( endIndex );
				result = result.Replace( endTag, block);
				return result;
			}
		}
		private string GetString(string org, string beginTag, string endTag)
		{
			return GetString(org, beginTag, endTag, "");
		}
		private string GetString(string org, string beginTag, string endTag, string repBegin)
		{
			int beginIndex, endIndex;
			string result;
			beginIndex	= org.IndexOf( beginTag, 0);
			endIndex		= org.IndexOf( endTag, 0);
			if (endIndex <= beginIndex)
			{
				return "";
			}
			else
			{
				result	= org.Substring( beginIndex, endIndex-beginIndex );
				result	= result.Replace( beginTag, repBegin);
				return result;
			}
		}
	}
}
